<template>
  <a-form-model
    ref="ruleForm"
    :model="newModelData"
    :rules="rules"
    layout="horizontal"
    class="AsteriskAfter newEditStyle rightDrawerWithoutCol"
  >
    <a-row :gutter="36">
      <a-col
        :md="8"
        :sm="24"
      >
        <a-form-model-item :label="$t('modelCode')" prop="code">
          <a-input
            :maxLength="15"
            :disabled="!!recordData.id || !modelInputMode"
            v-model="newModelData.code"
          />
        </a-form-model-item>
      </a-col>
      <a-col
        :md="8"
        :sm="24"
      >
        <a-form-model-item :label="$t('modelName')" prop="name">
          <!-- <div style="width: calc(100% - 50px);float:left;margin-right:10px"> -->
            <a-input v-if="modelInputMode" :maxLength="15"
              :disabled="!!recordData.id && (recordData.dataFrom === 'EXTERNAL' || remoteDataCopy.name !== remoteDataCopy.code)"
              v-model="newModelData.name"
              placeholder="新增车型名称"
            />
            <car-model-code-select v-else
              :query="{ time:instantUpdateTime, selectAll: true}"
              :has-all="false"
              :clear="true"
              mode="default"
              :disabled="!!recordData.id"
              v-model="newModelData.code"
              @changeoption="(code, model) => {setSelectedModel(model);$refs.ruleForm.validate()}" style="width:100%"
            ></car-model-code-select>
          <!-- </div> -->
          <template v-if="multiTrimLevel">
            <a @click="()=>{
              modelInputMode=!modelInputMode;
              setSelectedModel({})
              }" v-if="modelInputMode && !recordData.id">{{ $t('select') }}</a>
            <a @click="modelInputMode=!modelInputMode" v-if="!modelInputMode && !recordData.id">{{ $t('newly') }}</a>
          </template>
        </a-form-model-item>
      </a-col>
      <a-col
        :md="8"
        :sm="24"
      >
        <a-form-model-item label="品牌" prop="company">
<!--          新建时使用默认值，禁用；编辑时若已确认，禁用-->
          <CompanySelect v-model="newModelData.company" :disabled="disabledCompany"/>
        </a-form-model-item>
      </a-col>
      <a-col
        :md="24"
        :sm="24"
      >
        <a-form-model-item :label="$t('brandName')" prop="brandId">
          <a-select
            v-model="newModelData.brandId"
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            showSearch
            allow-clear
            :disabled="!modelInputMode"
          >
            <a-select-option
              v-for="(item,index) in brandData"
              :key="'brand-'+index"
              :value="item.id"
              :title="item.name"
            >{{ item.name }}</a-select-option>
          </a-select>
          <a
            style="position: absolute;right: 0;top: -38px;" v-if="!recordData.id && modelInputMode"
            @click="editBrand">{{ $t('edit') }}</a>
        </a-form-model-item>
      </a-col>
<!--      <a-col :md="8" :xs="24">-->
<!--        <a-form-model-item label="年款" prop="makeYear">-->
<!--          <a-select-->
<!--            :disabled="!!recordData.id"-->
<!--            v-model="newModelData.makeYear"-->
<!--            optionFilterProp="children"-->
<!--            :filterOption="$commonFun.filterOption"-->
<!--            showSearch-->
<!--            placeholder="年款"-->
<!--            allow-clear-->
<!--            style="width:100%"-->
<!--          >-->
<!--            <a-select-option-->
<!--              v-for="(item, index) in makeYearList"-->
<!--              :key="'my-'+index"-->
<!--              :value="item"-->
<!--              :title="item"-->
<!--            >{{ item }}</a-select-option-->
<!--            >-->
<!--          </a-select>-->
<!--        </a-form-model-item>-->
<!--      </a-col>-->
      <a-col :md="8" :xs="24">
        <a-form-model-item label="销售区域" prop="saleArea">
          <a-select
            v-model="newModelData.saleArea"
            optionFilterProp="children"
            :filterOption="$commonFun.filterOption"
            showSearch
            placeholder="销售区域"
            allow-clear
            style="width:100%"
          >
            <a-select-option
              v-for="(item, index) in saleArea"
              :key="'sa'+index"
              :value="item.value"
              :title="item.name"
            >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <!-- <a-row>
      <a-col :md="24" :sm="24">
        <a-form-model-item :label="$t('trimLevel')"></a-form-model-item>
      </a-col>
    </a-row> -->
    <!-- 新增的时候(款型列表) -->
    <!-- <div >
      <div style="margin: -38px 0 0 50px;float:left" v-if="!newModelData.id && multiTrimLevel">
        <a-tooltip title="添加款型">
          <a-button type="link" @click="addTrimLevel">
            <a-icon type="plus-circle" style="font-size: 22px"/>
          </a-button>
        </a-tooltip> -->
<!--        <a-button class="newBtnWithPlus" @click="addTrimLevel">+</a-button>-->
      <!-- </div> -->
      <!-- <div v-for="(trimLevel,i) in newModelData.trimLevel" :key="'tl-'+trimLevel.id" style="border-top:1px solid #f2f2f2;padding: 3px 0 20px 15px;">
        <a-row :gutter="16">
          <a-col
            :md="8"
            :sm="24"
          >
            <a-form-model-item :label="$t('stereotypeCode')" style="margin-bottom:0px"
                               :key="'trimLevel-code'+i"
                               :prop="'trimLevel.' + i + '.trimLevelCode'"
                               :rules="{required: true,validator: (rule, value, callback) => { $commonFun.commonValidator(rule, value, callback, 15) } , trigger: 'change'}">
              <a-input :maxLength="15" :disabled="!!newModelData.id" :placeholder="$t('stereotypeCode')" v-model="trimLevel.trimLevelCode" />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="24"
          >
            <a-form-model-item :label="$t('stereotype')" style="margin-bottom:0px"
                               :key="'trimLevel-name'+i"
                               :prop="'trimLevel.' + i + '.trimLevel'"
                               :rules="{required: true,validator: (rule, value, callback) => { $commonFun.commonValidator(rule, value, callback, 30) } , trigger: 'change'}">
              <a-input :maxLength="30" :placeholder="$t('stereotype')" v-model="trimLevel.trimLevel" :disabled="!!newModelData.id"/>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-model-item label="动力类型" prop="power" style="margin-bottom:0px;/*height:80px;*/">
              <a-select
                v-model="trimLevel.power"
                optionFilterProp="children"
                :filterOption="$commonFun.filterOption"
                showSearch
                placeholder="动力类型"
                allow-clear
                style="width:calc(100% - 60px);margin-right:16px;"
              >
                <a-select-option
                  v-for="(item, index) in powerType"
                  :key="'power-'+index"
                  :value="item.value"
                  :title="item.name"
                >{{ item.name }}</a-select-option
                >
              </a-select>
              <a @click="handleDelete(trimLevel.id)" v-if="newModelData.trimLevel.length > 1 && !recordData.id">{{ $t('delete') }}</a>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="22" :offset="2" style="height:20px" v-if="!hideConfigModel">
            <label style="font-size: 1.2rem;font-weight: bold;color: #5e5e5e;">配置车型</label>
            <a-tooltip title="添加配置车型" v-if="!newModelData.id">
              <a-button type="link" @click="trimLevel.configModels.push({})">
                <a-icon type="plus-circle" style="font-size: 18px"/>
              </a-button>
            </a-tooltip>
          </a-col>
          <template v-for="(configModel,index) in trimLevel.configModels" >
            <a-col
              :md="7"
              :sm="23"
              :offset="2" v-if="!hideConfigModel"
            >
              <a-form-model-item :label="''" style="margin-bottom:0"
                                 :key="'configModel-code'+index"
                                 :prop="'trimLevel.'+i+'.configModels.' + index + '.code'"
                                 :rules="{required: true,validator: (rule, value, callback) => { $commonFun.commonValidator(rule, value, callback, 20) } , trigger: 'change'}">
                <a-input :maxLength="20" :disabled="!!newModelData.id" placeholder="配置车型代码" v-model="configModel.code" />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="7"
              :sm="23" v-if="!hideConfigModel"
            >
              <a-form-model-item :label="''" style="margin-bottom:0"
                                 :key="'configModel-name'+index"
                                 :prop="'trimLevel.'+i+'.configModels.' + index + '.name'"
                                 :rules="{required: true,validator: (rule, value, callback) => { $commonFun.commonValidator(rule, value, callback, 20) } , trigger: 'change'}">
                <a-input :maxLength="20" :disabled="!!newModelData.id" placeholder="配置车型名称" v-model="configModel.name" />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="8"
              :sm="23"
            >
              <a-form-model-item :label="'公告型号'" style="margin-bottom:0">
                <template v-if="!hideConfigModel">
                  <a-input :maxLength="20" placeholder="公告型号" v-model="configModel.publishCode"
                           style="width:calc(100% - 60px);margin-right:16px;"/>
                  <a @click="trimLevel.configModels.splice(trimLevel.configModels.indexOf(configModel), 1)"
                     v-if="trimLevel.configModels.length > 1 && !recordData.id">{{ $t('delete') }}</a>
                </template>
                <template v-else>
                  <a-input :maxLength="20" placeholder="公告型号" v-model="configModel.publishCode"
                           style="width:100%;"/>
                </template>

              </a-form-model-item>
            </a-col>
          </template>
        </a-row>
      </div> -->

    <!-- </div> -->
    <!-- 编辑的时候(款型是一个,且只能查看) -->
<!--    <a-row :gutter="16" v-else>-->
<!--      <a-col-->
<!--        :md="8"-->
<!--        :sm="24"-->
<!--      >-->
<!--        <a-form-model-item :label="''" prop="trimLevel">-->
<!--          <a-input :disabled="true" :placeholder="$t('stereotypeCode')" v-model="newModelData.trimLevelCode" />-->
<!--        </a-form-model-item>-->
<!--      </a-col>-->
<!--      <a-col-->
<!--        :md="16"-->
<!--        :sm="24"-->
<!--      >-->
<!--        <a-form-model-item :label="''" prop="trimLevel">-->
<!--          <a-input :disabled="true" :placeholder="$t('stereotype')" v-model="newModelData.trimLevel" />-->
<!--        </a-form-model-item>-->
<!--      </a-col>-->
<!--    </a-row>-->
  </a-form-model>

</template>
<script>
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { mapMutations, mapState } from 'vuex'
import { checkTextLen } from '@/utils/validate'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import NewEditBrand from "./NewEditBrand";
import lodash from "lodash";
import CompanySelect from '@/views/components/companySelect'

const oneTrimLevel = {
  trimLevel: '',
  trimLevelCode: '',
  configModels: [{
    code: 'NA',
    name: '默认配置车型',
    publishCode: ''
  }]
}
let makeYearList=[];
for (var i = 0; i < 100; i++) {
  makeYearList.push('20' + (i+"").padStart(2, '0'))
}
export default {
  name: 'NewEditModel',
  components: { tableEllipsis,CarModelCodeSelect,CompanySelect },
  props: {
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    isBack: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState({
      powerType: (state) => state.dict.powerTypeDictCode,
      saleArea: (state) => state.dict.saleAreaDictCode,
      newModelData: state => state.model.newModelData,
      brandData: (state) => state.brand.brandData,
      instantUpdateTime: (state) => state.app.instantUpdateTime
    })
  },
  data () {
    return {
      modelInputMode: true,//车型代码输入类型：选择(false)/输入 (true)
      hideConfigModel: true, //隐藏配置车型信息，目前先不维护配置车型信息
      multiTrimLevel: false, //是否支持车型下多款型
      remoteDataCopy: null, // 服务器数据副本
      makeYearList: makeYearList,
      rules: {
        name: [{ required: true, validator: (rule, value, callback) => { this.$commonFun.commonValidator(rule, value, callback, 15) }, trigger: ['change', 'blur'] }],
        code: [{ required: true, validator: (rule, value, callback) => { this.$commonFun.commonValidator(rule, value, callback, 15) }, trigger: ['change', 'blur'] }],
        brandId: [{ required: true, message: this.$t('pleaseSelect') , trigger: ['change', 'blur']}],
        company: [{ required: true, message: this.$t('pleaseSelect'), trigger: ['change', 'blur']}],
        // trimLevel: [{ validator: checkTextLen() }]
      },
      newModelBrand: [], // 品牌列表
      disabledCompany: false
    }
  },
  created () {
    if (this.recordData.model && this.recordData.model.company && this.recordData.model.company === 'UNKNOWN') {
      this.disabledCompany = false
    } else if (this.recordData.id) {
      this.disabledCompany = true
    } else {
      this.disabledCompany = false
    }
    this.initForm()
  },
  mounted() {
    this.$store.dispatch('getPowerTypeDictCodeData');
    this.$store.dispatch('getSaleAreaDictCodeData');
  },
  methods: {
    ...mapMutations([
      'SET_NEWMODEL_DATA',
      'SET_ModelRightDrawerEvent',
      // 'setInstantUpdateTime'
    ]),
    // 删除单行
    handleDelete (id) {
      const vm = this
      this.submitDisabled = false
      vm.newModelData.trimLevel = vm.newModelData.trimLevel.filter(item => {
        return item.id !== id
      })
    },
    // 新增款型
    addTrimLevel () {
      this.newModelData.trimLevel.push(this.getOneTrimLevel())
    },
    // 初始化表单
    initForm () {
      const vm = this
      if (vm.isBack) {
          // 由编辑车系返回的
          this.modelInputMode = true;
          return;
      }
      vm.$refs.ruleForm && vm.$refs.ruleForm.resetFields()
      vm.$refs.ruleForm && vm.$refs.ruleForm.clearValidate()
      if (vm.recordData.id) {
      // 编辑
        vm.getModelDetail().then(() => {
          this.modelInputMode = true
        })
      } else if (!this.recordData.code) {
        // 新增
        vm.SET_NEWMODEL_DATA({
          trimLevel: [{
            trimLevel: '默认款型',
            trimLevelCode: 'NA',
            configModels: [{
              code: 'NA',
              name: '默认配置车型',
              publishCode: ''
            }]
          }]
        });
      } else {
        // 克隆新增
        var data = {...vm.recordData.model};
        data.trimLevel = [{
          // id: vm.recordData.model.id,
          trimLevel: vm.recordData.model.trimLevel,
          trimLevelCode: vm.recordData.model.trimLevelCode,
          power: vm.recordData.model.power,
          configModels: [{
            // id: vm.recordData.id,
            code: vm.recordData.code,
            name: vm.recordData.name,
            publishCode: vm.recordData.publishCode,
          }]
        }]
        this.modelInputMode = true
        this.$nextTick(() =>{
          this.SET_NEWMODEL_DATA(data)
        })
        // this.setInstantUpdateTime();
      }
      this.setSelectedModel({})
    },
    getOneTrimLevel () {
      return {
        ...lodash.cloneDeep(oneTrimLevel),
        id: 'id-' + Math.random()
      }
    },
    // 获取车型详情
    getModelDetail () {
      return this.$api.getConfigModelDetail({ id: this.recordData.id }).then((res) => {
        var data = {...res.data.model};
        data.saleArea = res.data.model.saleArea || undefined
        data.trimLevel = [{
          id: res.data.model.id,
          trimLevel: res.data.model.trimLevel,
          trimLevelCode: res.data.model.trimLevelCode,
          power: res.data.model.power||undefined,
          configModels: [{
            id: res.data.id,
            code: res.data.code,
            name: res.data.name,
            publishCode: res.data.publishCode,
          }]
        }]
        this.remoteDataCopy = {...data};
        this.SET_NEWMODEL_DATA(data)
      }).catch((e) => vm.$message.error("获取车型信息失败！"))
    },
    // 获取品牌
    getBrandList () {
      this.$store.dispatch('getBrandData')
    },
    // 编辑品牌
    editBrand () {
      this.SET_ModelRightDrawerEvent('newBrand')
    },
    getFormData () {
      const vm = this
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate(valid => {
          if (!valid) {
            reject(valid)
            return
          }
          if (vm.newModelData.id) {
            // 编辑的时候
            resolve(vm.newModelData)
            return
          }
          const trimLevel = vm.newModelData.trimLevel.filter(item => {
            // eslint-disable-next-line no-param-reassign
            item.trimLevel = item.trimLevel.trim()
            // eslint-disable-next-line no-param-reassign
            item.trimLevelCode = item.trimLevelCode.trim()
            if (item.trimLevel.length === 0 && item.trimLevelCode.length === 0) {
              return false
            }
            return true
          })
          if (trimLevel.length && this.checkTrimLevel(trimLevel)) {
            this.$message.error(this.$t('trimLevelInputTip'))
            return
          }
          resolve({ ...vm.newModelData, trimLevel: trimLevel.length ? trimLevel : null })
        })
      })
    },
    // 检测款型(款型名称与款型代码只有任务一个有值只需要填写完整)
    checkTrimLevel (data) {
      if (this.newModelData.id) {
        // 编辑的时候不需要检测
        return true
      }
      const result = data.some(item => {
        const { trimLevel } = item
        const { trimLevelCode } = item
        if (trimLevel.length === 0 && trimLevelCode.length === 0) {
          return true
        }
        if (trimLevel.length === 0) {
          return true
        }
        if (trimLevelCode.length === 0) {
          return true
        }
        return false
      })
      return result
    },
    setSelectedModel(model= {}) {
      this.newModelData.code = model.code || undefined;
      this.newModelData.name = model.name || undefined;
      this.newModelData.brandId=model.brandId || undefined;
      this.newModelData.brandName=model.brandName || undefined;
      // this.newModelData.company=model.company || undefined;
      // this.$refs.ruleForm.validate()
    }
  },
  watch: {
    brandData(newV){
      if (!!this.newModelData.brandId && newV && newV.length != 0) {
        let index = newV.findIndex(e => e.id == this.newModelData.brandId)
        if (index == -1) {
          this.newModelData.brandId = undefined
        }
      }
    },
    instantUpdateTime: {
      handler () {
        const vm = this
        // vm.initForm()
        vm.getBrandList()
      },
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped>
  .newBtnWithPlus{
  }
</style>
